package com.zdwhong.mysqlms.multidatasource;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author ZDW
 * @since 2021-05-25 18:57
 */
@Slf4j
@Aspect
@Component
@Order(1)//配置注解优先级，优于事物注解@Transactional先进行数据源切换，//不然在事物中进行数据源切换无效
public class DataSourceAop {

    @Pointcut("@annotation(com.zdwhong.mysqlms.multidatasource.Slave)")
//    @Pointcut("execution(* com.zdwhong.mysqlms..*.select*(..)) " +
//            "|| execution(* com.zdwhong.mysqlms..*.find*(..)) " +
//            "|| execution(* com.zdwhong.mysqlms..*.get*(..)) " +
//            "|| execution(* com.zdwhong.mysqlms..*.list*(..)) ")
    public void readPointcut() {

    }



    @Pointcut("@annotation(com.zdwhong.mysqlms.multidatasource.Master)")
//    @Pointcut("execution(* com.zdwhong.mysqlms..*.insert*(..)) " +
//            "|| execution(* com.zdwhong.mysqlms..*.update*(..)) " +
//            "|| execution(* com.zdwhong.mysqlms..*.save*(..)) " +
//            "|| execution(* com.zdwhong.mysqlms..*.delete*(..)) ")
    public void writePointcut() {

    }

    @Before("readPointcut()")
    public void read() {
        //获取拦截类
        log.info("read operate");
        DBContextHolder.slave();
        log.info(Thread.currentThread().getName()+" 获取到数据源："+DBContextHolder.get());
    }

    @Before("writePointcut()")
    public void write() {
        //获取拦截类
        /* String className = pjp.getTarget().getClass().getName();
       System.out.println("当前线程"+Thread.currentThread().getName()+" 拦截类为：" + className);

       //获取拦截的方法名
       MethodSignature msig = (MethodSignature) pjp.getSignature();
       Method currentMethod = null;
       try {
           currentMethod = pjp.getTarget().getClass().getMethod(msig.getName(), msig.getParameterTypes());
       } catch (NoSuchMethodException e) {
           e.printStackTrace();
       }
       String methodName = currentMethod.getName();
       System.out.println("拦截方法名为：" + methodName);*/
        log.info("write operate");
        DBContextHolder.master();
        log.info(Thread.currentThread().getName()+" 获取到数据源："+DBContextHolder.get());
    }

    @After("writePointcut(),readPointcut()")
    public void clean() {
        log.info("dataSource cleanAll");
        DBContextHolder.cleanAll();
    }
}
